package com.shop.cereshop.agent.service.product.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.agent.dao.behavior.AgentBehaviorDAO;
import com.shop.cereshop.agent.dao.product.AgentProductImageDAO;
import com.shop.cereshop.agent.dao.product.AgentProductSkuDAO;
import com.shop.cereshop.agent.page.product.AgentProductSkuVO;
import com.shop.cereshop.agent.page.product.AgentSkuValueVO;
import com.shop.cereshop.agent.page.product.SkuAttributeVO;
import com.shop.cereshop.agent.page.product.ProductDetailVO;
import com.shop.cereshop.agent.page.product.ProductParam;
import com.shop.cereshop.agent.param.product.ProductListDTO;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.domain.agentProduct.CereAgentProduct;
import com.shop.cereshop.commons.domain.agentProduct.CereAgentProductImage;
import com.shop.cereshop.commons.domain.agentSearch.CereAgentSearchHistory;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.common.PageParam;
import com.shop.cereshop.commons.domain.order.CereAgentOrderProduct;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.agent.dao.product.CereAgentProductDAO;
import com.shop.cereshop.agent.dao.search.CereAgentSearchHistoryDAO;
import com.shop.cereshop.agent.page.product.ProductVO;
import com.shop.cereshop.agent.param.product.ProductDTO;
import com.shop.cereshop.agent.param.search.SearchDTO;
import com.shop.cereshop.agent.service.product.ProductService;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class ProductServiceImpl extends ServiceImpl<CereAgentProductDAO, CereAgentProduct> implements ProductService {
  @Autowired
  private CereAgentProductDAO cereAgentProductDAO;

  @Autowired
  private CereAgentSearchHistoryDAO cereAgentSearchHistoryDAO;

  @Autowired
  private AgentProductImageDAO agentProductImageDAO;

  @Autowired
  private AgentProductSkuDAO agentProductSkuDAO;

  @Resource
  private AgentBehaviorDAO agentBehaviorDAO;

  @Override
  public Page<CereAgentSearchHistory> getSearchHistoryList(SearchDTO searchDTO) {
    PageHelper.startPage(searchDTO.getPage(), searchDTO.getPageSize());
    List<CereAgentSearchHistory> searchHistoryList = cereAgentSearchHistoryDAO
        .selectHistoryList(searchDTO.getAgentId());
    PageInfo<CereAgentSearchHistory> cereAgentSearchHistoryPageInfo = new PageInfo<>(searchHistoryList);
    Page<CereAgentSearchHistory> cereAgentSearchHistoryPage = new Page<>(cereAgentSearchHistoryPageInfo.getList(),
        cereAgentSearchHistoryPageInfo.getTotal());
    return cereAgentSearchHistoryPage;
  }

  @Override
  public boolean deleteSearchHistory(SearchDTO searchDTO) {
    cereAgentSearchHistoryDAO.deleteHistory(searchDTO.getHistoryId(), searchDTO.getAgentId());
    return true;

  }

  @Override
  public ProductDetailVO getProductDetail(Long productId, Long agentUserId) {
    // 1、查询基础参数和销量
    ProductDetailVO producerDetail = cereAgentProductDAO.getProducerDetail(productId);

    // 2、查询轮播图
    List<String> images = agentProductImageDAO.getProductImages(productId);

    // 3、查询是否收藏
    Integer collected = agentBehaviorDAO.getCollectState(agentUserId, productId);
    if (collected == null) {
      collected = IntegerEnum.NO.getCode();
    }

    // 4、查询商品参数
    List<ProductParam> productParams = cereAgentProductDAO.getProductParams(productId);

    // 5、查询商品规格列表
    List<AgentProductSkuVO> skuList = agentProductSkuDAO.getProductSkuList(productId);

    // 6、一次遍历完成所有操作：获取价格、构建规格数据
    if (!EmptyUtils.isEmpty(skuList)) {
      Map<String, List<AgentSkuValueVO>> nameValueGroups = new HashMap<>();
      Map<String, AgentProductSkuVO> skuQuickMap = new HashMap<>();
      Set<String> skuNames = new HashSet<>();

      for (AgentProductSkuVO sku : skuList) {
        // 1. 获取默认规格价格（只需第一次）
        if (producerDetail.getPrice() == null && sku.getIfDefault() != null && sku.getIfDefault() == 1) {
          producerDetail.setPrice(sku.getPrice());
          producerDetail.setOriginalPrice(sku.getOriginalPrice());
        }

        // 2. 构建 SKU 快速查询表
        if (!EmptyUtils.isEmpty(sku.getValue())) {
          skuQuickMap.put(sku.getValue(), sku);
        }

        // 3. 构建规格分组
        if (!EmptyUtils.isEmpty(sku.getSpecs())) {
          for (SkuAttributeVO attr : sku.getSpecs()) {
            String skuName = attr.getSkuName();
            String skuValue = attr.getSkuValue();

            skuNames.add(skuName);

            // 构建规格名下的规格值列表（去重）
            List<AgentSkuValueVO> values = nameValueGroups.computeIfAbsent(
                skuName, k -> new ArrayList<>());

            // 检查规格值是否已存在
            boolean exists = values.stream()
                .anyMatch(v -> v.getSkuValue().equals(skuValue));

            if (!exists) {
              AgentSkuValueVO valueVO = new AgentSkuValueVO();
              valueVO.setSkuName(skuName);
              valueVO.setSkuValue(skuValue);
              values.add(valueVO);
            }
          }
        }
      }

      // 设置规格相关字段
      producerDetail.setSkus(skuList);
      producerDetail.setNameValueGroups(nameValueGroups);
      producerDetail.setSkuQuickMap(skuQuickMap);
      producerDetail.setSkuNames(skuNames);
    }

    producerDetail.setProductImage(images);
    producerDetail.setIfCollect(collected);
    producerDetail.setProductParams(productParams);

    return producerDetail;
  }

  @Override
  public List<ProductVO> getProducts(ProductListDTO param) {
    if (param.getPage() == null || param.getPage() < 1) {
      // 分页参数为空则设置默认分页
      param.setPage(1);
      param.setPageSize(10);
    }

    // 如果输入了搜索关键字，则记录搜索历史
    if (!EmptyUtils.isEmpty(param.getSearch()) && param.getAgentUserId() != null) {
      // 过滤表情包参数
      String search = EmptyUtils.filterEmoji(param.getSearch());

      // 查询当前搜索记录是否存在
      CereAgentSearchHistory searchHistory = cereAgentSearchHistoryDAO.getSearchHistoryByUserId(
          param.getAgentUserId(), search);
      if (searchHistory == null) {
        // 如果没有，新增搜索记录
        CereAgentSearchHistory newSearchHistory = new CereAgentSearchHistory();
        newSearchHistory.setAgentUserId(param.getAgentUserId());
        newSearchHistory.setSearchKeyword(search);
        newSearchHistory.setSearchTime(LocalDateTime.now());
        newSearchHistory.setDeleted(IntegerEnum.DELETED_NO.getCode());
        newSearchHistory.setNumber(1L);
        cereAgentSearchHistoryDAO.insert(newSearchHistory);
      } else {
        // 如果存在，更新搜索次数
        Long number = searchHistory.getNumber();
        number++;
        searchHistory.setNumber(number);
        searchHistory.setSearchTime(LocalDateTime.now());
        cereAgentSearchHistoryDAO.updateById(searchHistory);
      }
    }

    // 构建分页参数
    PageHelper.startPage(param.getPage(), param.getPageSize());
    return cereAgentProductDAO.getProducts(param);
  }

}
